import socket, sppt, socketev

class exposed():
	def __init__(self):
		self.socket = None
		self.client = None
		self.connected = False
		self.protocolName = "bnftp.py"
		self.parent = None
		
	def OnSending(self, owner, data):
		sppt.write("Sending (server) [%s]: %i" % (self.protocolName, len(data)))
		# Sending to server | from application
		pass
		
	def OnSend(self, owner, data):
		sppt.write("Send (server) [%s]: %i" % (self.protocolName, len(data)))
		# Send to server | from application
		pass
		
	def OnRecv(self, owner, data):
		sppt.write("Recv (server) [%s]: %i" % (self.protocolName, len(data)))
		# Send to client | from server
		self.parent.client.send(data)
		
	def OnDisconnect(self, owner, text):
		sppt.write("Disconnect (server) [%s]: %s" % (self.protocolName, text))
		
	def Invoke(self, event, args):
		# Communication from the listener. Battle.net is seperate.
		if (event == "OnStart"):
			self.parent = args[0]
			# We need to connect, listener is starting
			self.socket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
			self.socket.settimeout(15.0)
			sppt.write("[BNFTP] Connecting to Battle.net...")
			try:
				self.socket.connect( ("uswest.battle.net", 6112) )
			except socket.herror:
				sppt.write("[BNFTP] Socket error")
				return False
			except socket.timeout:
				sppt.write("[BNFTP] Socket timout")
				return False
			except:
				sppt.write("[BNFTP] Unknown error")
				return False
			sppt.write("[BNFTP] Connected!")
			self.socket.settimeout(300.0)
			self.client = socketev.socket_ev(self.OnRecv, self.OnSending, self.OnSend, self.OnDisconnect, self.socket, self.protocolName)
		elif (event == "OnRecv"):
			# Send to server | from client
			self.client.send(args[1])
		elif (event == "OnSending"):
			# Sending to client | from application
			pass
		elif (event == "OnSend"):
			# Send to client | from application
			pass
			